package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.common.R;
import com.itheima.common.ValidateCodeUtils;
import com.itheima.entity.User;
import com.itheima.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;

    @Autowired
    RedisTemplate redisTemplate;

    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user) {
        String phone = user.getPhone();
        if (phone != null && phone.length() > 0){
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("code={}",code);
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
//            httpSession.setAttribute(phone,code);
            return R.success("手机验证码短信发送成功");
        }
        return R.error("发送验证码失败");
    }

    @PostMapping("/login")
    public R<User> login (@RequestBody Map map, HttpServletRequest request){
        //获取session
        String phone = map.get("phone").toString();
//        Object attribute = request.getSession().getAttribute(phone);
        Object attribute = redisTemplate.opsForValue().get(phone);
        //判断非空,验证码是否匹配
        String code = map.get("code").toString();
        if (attribute != null && attribute.equals(code)){
            //查询用户
            LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
            lqw.eq(User::getPhone,phone);
            User one = userService.getOne(lqw);
            //数据库没有该用户就添加
            if (one == null){
                User user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }
            request.getSession().setAttribute("user",one.getId());
            redisTemplate.delete(phone);
            return R.success(one);
        }
        return R.error("登录失败");
    }

    @PostMapping("/loginout")
    public R<String> loginout(HttpServletRequest request){
        request.getSession().removeAttribute("user");
        return R.success("退出成功");
    }
}
